﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace XwOa
{
    internal class Decrypt
    {
        private static readonly byte[] ExecuteKeys = { 0x06, 0x66, 0x19, 0x86, 0x10, 0x24, 0x17, 0x17 };

        /// <summary>
        ///     密钥：@666GPS#
        /// </summary>
        private const string EncryptKey = "@666GPS#";

        /// <summary>
        ///     DES加密字符串
        /// </summary>
        /// <param name="encryptStr">待加密的字符串</param>
        /// <returns>加密成功返回加密后的字符串，失败返回源串</returns>
        public static string EncryptDes(string encryptStr)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(EncryptKey.Substring(0, 8));
                byte[] rgbIv = ExecuteKeys;
                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptStr);

                using (DESCryptoServiceProvider dCsp = new DESCryptoServiceProvider())
                {
                    using (MemoryStream mStream = new MemoryStream())
                    {
                        using (CryptoStream cStream = new CryptoStream(mStream, dCsp.CreateEncryptor(rgbKey, rgbIv), CryptoStreamMode.Write))
                        {
                            cStream.Write(inputByteArray, 0, inputByteArray.Length);
                            cStream.FlushFinalBlock();
                        }
                        return Convert.ToBase64String(mStream.ToArray());
                    }
                }
            }
            catch
            {
                return encryptStr;
            }
        }

        /// <summary>
        ///     DES解密字符串
        /// </summary>
        /// <param name="decryptStr">待解密的字符串</param>
        /// <returns>解密成功返回解密后的字符串，失败返源串</returns>
        public static string DecryptDes(string decryptStr)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(EncryptKey);
                byte[] rgbIv = ExecuteKeys;
                byte[] inputByteArray = Convert.FromBase64String(decryptStr);

                using (DESCryptoServiceProvider dcsp = new DESCryptoServiceProvider())
                {
                    using (MemoryStream mStream = new MemoryStream())
                    {
                        using (CryptoStream cStream = new CryptoStream(mStream, dcsp.CreateDecryptor(rgbKey, rgbIv), CryptoStreamMode.Write))
                        {
                            cStream.Write(inputByteArray, 0, inputByteArray.Length);
                            cStream.FlushFinalBlock();
                        }
                        return Encoding.UTF8.GetString(mStream.ToArray());
                    }
                }
            }
            catch
            {
                return decryptStr;
            }
        }
    }
}